package com.filepublic.demo.server.service.impl;

import com.filepublic.demo.common.constant.RedisKeyConstant;
import com.filepublic.demo.common.constant.RedisTimeConstant;
import com.filepublic.demo.common.util.EmailUtil;
import com.filepublic.demo.server.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AsyncServiceImpl implements AsyncService {

    @Resource
    JavaMailSender javaMailSender;

    @Resource
    RedisTemplate redisTemplate;

    /**
     * 异步发送验证码邮件
     */
    @Async("myAsyncThreadPool")
    public void sendEmail(String emailUser) {
        log.info("异步发送验证码");
        //redis的Key生成
        String captchaKey = RedisKeyConstant.CAPTCHA_KEY +emailUser;

        //生成发送的消息
        SimpleMailMessage message = EmailUtil.buildText(emailUser);

        //生成验证码
        String captcha = EmailUtil.buildCaptcha();

        //保存到redis
        redisTemplate.opsForValue().set(captchaKey, captcha, RedisTimeConstant.CAPTCHA_TIME, TimeUnit.MILLISECONDS);

        //为消息设置email内容
        message.setText("这是你的登录验证码："+captcha);

        //发送邮件
        javaMailSender.send(message);
    }

    /**
     * 异步保存文件
     */
    @Async("myAsyncThreadPool")
    public void saveFile(MultipartFile file, File saveFilePath) throws IOException {
        file.transferTo(saveFilePath);
    }
}
